<?php

namespace app\model;

use app\common\service\redis\PoolRedis;
use think\facade\Log;
use think\model\relation\BelongsTo;

class AdminSchoolRkeRecord extends Base {

    const SCHOOL_RKE_RECORD_KEY = 'school_rke_unlock_count:';

    const SERIAL_TYPE = [1 => '门禁', 2 => '人脸一体机'];
    const DOOR_LOCATION = [1 => '大门'];
    const CARD_TYPE = [0=>'刷卡',1 => '二维码', 2=> '密码器',3=> '按钮', 6=> '身份证',9=>'二维码',10=>'指纹',11=>'指静脉',12=>'RFID卡',13=>'人脸'];
    const ACS_STATUS = [0=>'拒绝打开',1 => '允许打开'];
    const ACT_FLAG = [0=>'进',1 => '出',2=>'报警'];


    public function school(): BelongsTo {
        return $this->belongsTo(AdminSchool::class, 'school_id')->bind([
            'school_name' => 'name'
        ]);
    }

    public function staff(): BelongsTo {
        return $this->belongsTo(AdminStaff::class, 'staff_id');
    }

    public function getSerialTypeTextAttr($value, $data)
    {
        $type = self::SERIAL_TYPE;
        return $type[$data['serial_type']] ?? '';
    }

    public function getDoorLocationLabelAttr($value, $data)
    {
        $type = self::DOOR_LOCATION;
        return $type[$data['door_location']] ?? '';
    }

    public function getCardTypeTextAttr($value, $data)
    {
        $type = self::CARD_TYPE;
        return $type[$data['card_type']] ?? '';
    }

    public function getAcsResTextAttr($value, $data)
    {
        $type = self::ACS_STATUS;
        return $type[$data['acs_res']] ?? '';
    }

    public function getActIndexTextAttr($value, $data)
    {
        $type = self::ACT_FLAG;
        return $type[$data['act_index']] ?? '';
    }

    public static function onAfterInsert($AdminSchoolRkeRecord)
    {
        $staff = $AdminSchoolRkeRecord->staff;
        $countKey = self::SCHOOL_RKE_RECORD_KEY.date('Y-m-d')."_".$AdminSchoolRkeRecord->school_id;
        $hour_index = ceil(date('G') / 3);
        $hour_index = $hour_index > 0 ? ($hour_index-1)*3 : 0;
        $redis = PoolRedis::instance();
        $redis->hIncrBy($countKey, $staff->sex.":".$hour_index."-".($hour_index+3), 1);
        $redis->expire($countKey, 1*24*60*60);

        // 修改学生最后操作门闸的状态和时间
        AdminStaff::update([
            'last_control_status' => $AdminSchoolRkeRecord->act_index,
            'last_control_time'=>time()], ['id' => $staff->id]);
    }

    // 缓存门禁开锁统计barData数据
    public static function addRkeRecode()
    {
        $countKey = self::SCHOOL_RKE_RECORD_KEY.date('Y-m-d')."_";
        $redis = PoolRedis::instance();

        $subsql = (new AdminSchoolRkeRecord())->alias('asr')
            ->join(["admin_staff" => 'af'], 'af.id = asr.staff_id')
            ->whereDay('asr.create_time')
            ->where('asr.acs_res', 1)
            ->field('asr.school_id,af.sex,floor(HOUR(FROM_UNIXTIME(asr.create_time, "%Y-%m-%d %H:%i%:%s")) / 3) as hour_index,count(1)as hour_amount')
            ->group('asr.school_id,af.sex,floor(HOUR(FROM_UNIXTIME(asr.create_time, "%Y-%m-%d %H:%i%:%s")) / 3)')
            ->buildSql();
        $list = (new AdminSchool())->alias('ac')
            ->leftJoin([$subsql=> 'ar'], 'ar.school_id = ac.id')
            ->where('ac.is_delete', 0)
            ->field('ac.id,ac.name,ar.hour_index,ar.sex,sum(ar.hour_amount)hour_amount')
            ->group("ac.id,ar.sex,ar.hour_index")
            ->having("hour_amount > 0")
            ->select()->toArray();
        $redis->multi(\Redis::PIPELINE);
        foreach ($list as $item) {
            $hour_index = $item['hour_index'] ? $item['hour_index']."-".($item['hour_index']+3) : '0-3';
            $sex = $item['sex'] ? $item['sex'] : '男';
            $redis->hSet($countKey.$item['id'], $sex.":".$hour_index, $item['hour_amount']);
            $redis->expire($countKey.$item['id'], 1*24*60*60);
        }
        $redis->exec();
    }

    // 把time按指定长度进行分组
    public static function groupTime($splice, $time = 24)
    {
        $arr = [];
        for ($i = 0; $i < $time; $i+=$splice) {
            $arr[$i."-".($i+$splice)] = ['label' => $i."-".($i+$splice)."h", 'value' => 0];
        }
        return $arr;
    }
}
